from nonebot import on_command, CommandSession, get_bot, on_notice, NoticeSession
from nonebot.permission import SUPERUSER
import asyncio
import re  # 引入正则表达式模块
from datetime import datetime
import json
import os

# 获取当前脚本的绝对路径

script_path = os.path.abspath(__file__)
# 获取当前脚本的父目录的父目录
parent_parent_dir = os.path.dirname(os.path.dirname(script_path))
# 指定json文件的路径
json_path = os.path.join(parent_parent_dir, 'data.json')

print(f'json_path: {json_path}')

bot = get_bot()

# 使用字典存储关键字和对应的QQ号
keywords = {}
last_forwarded_message = None

if os.path.exists(json_path):
    with open(json_path, 'r', encoding='utf-8') as f:
        data = json.load(f)
        keywords = data['keywords']
        print(f'从文件中读取到的关键字: {keywords}')
# 定义开始转发命令
@on_command('开始转发', permission=SUPERUSER)
async def start_forwarding(session: CommandSession):
    global keywords
    keyword = session.current_arg_text.strip()
    if not keyword:
        keyword = await session.aget('keyword', prompt='你想要转发哪个关键字的消息？')
    #user_id = session.get('user_id', prompt='你想要将消息转发到哪个QQ号？')
    user_id = 169325092  # 直接将QQ号设置为169325092
    keywords[keyword] = user_id
    write_keywords_to_file(keywords, json_path)
    await session.send(f'已开始转发关键字"{keyword}"的消息到QQ号"{user_id}"。')
# 定义停止转发命令
@on_command('清空转发', permission=SUPERUSER)
async def stop_forwarding(session: CommandSession):
    global keywords
    keywords = {}
    await session.send('已清空转发所有关键字的消息。')
    write_keywords_to_file(keywords, json_path)

# 定义删除转发命令
@on_command('删除转发',aliases=('停止转发','暂停转发'),permission=SUPERUSER)
async def delete_forwarding(session: CommandSession):
    global keywords
    keyword = session.current_arg_text.strip()
    if not keyword:
        keyword = await session.aget('keyword', prompt='你想要删除哪个关键字的转发？')
    if keyword in keywords:
        del keywords[keyword]
        write_keywords_to_file(keywords, json_path)
        await session.send(f'已删除关键字"{keyword}"的转发。')
    else:
        await session.send(f'关键字"{keyword}"没有被转发。')

# 定义当前转发命令
@on_command('当前转发', aliases=('正在转发'), permission=SUPERUSER)
async def current_forwarding(session: CommandSession):
    global keywords
    if keywords:
        # await session.send('当前正在转发以下关键字的消息：' + ', '.join(f'"{k}": "{v}"' for k, v in keywords.items()))
        await session.send('当前正在转发以下关键字的消息：' + ', '.join(f'"{k}"' for k in keywords.items()))
    else:
        await session.send('当前没有正在转发的关键字。')


def write_keywords_to_file(keywords, json_path):
    try:
        with open(json_path, 'w', encoding='utf-8') as f:
            json.dump({'keywords': keywords}, f,ensure_ascii=False)
    except IOError as e:
        print(f"无法写入文件 {json_path}: {e}")


# 定义处理群聊消息的函数
@bot.on_message('group')
async def handle_group_message(ctx):
    global keywords
    global last_forwarded_message  # 引入全局变量
    message = ctx['message']  # 获取 Message 对象
    # print(f'收到群消息: {message}')  # 打印接收到的消息

    message_text = str(message)  # 将 Message 对象转换为字符串
    message_content = message_text

    if message_content == last_forwarded_message:  # 如果这条消息与上一次转发的消息相同，就跳过这条消息
        return
    last_forwarded_message = message_content  # 更新上一次转发的消息

    for keyword, user_id in keywords.items():
        if re.search(keyword, message_text, re.IGNORECASE):  # 使用正则表达式进行匹配，忽略大小写

            sender_id = ctx['sender']['user_id']
            group_id = ctx['group_id']
            time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')  # 获取当前时间

            print(f'关键字 "{keyword}" 在 "{message}"找到. 尝试发送到 QQ "{user_id}".')

            try:
                group_info = await bot.get_group_info(group_id=group_id)
                group_name = group_info['group_name']

                sender_info = await bot.get_stranger_info(user_id=sender_id)
                sender_nickname = sender_info['nickname']

                print(f'群名: {group_info}')
                print(f'发送者qq号: {sender_info}')
            except Exception as e:
                print(f'获取群名或者昵称错误: {e}')
                continue

            try:
                await bot.send_private_msg(user_id=user_id,
                                           message=f'群名称: {group_name}\n发送者: {sender_nickname} (QQ: {sender_id})\n发送时间: {time}\n消息: {message}')
                print('Message sent successfully.')
            except Exception as e:
                print(f'Error sending message: {e}')
